
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using System.Linq;
using System.Linq.Dynamic;
using System.Linq.Expressions;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;

using System.Linq.Dynamic.Core;
 using Microsoft.EntityFrameworkCore; 

using DualControl.CompanyInfos.Authorization;
using DualControl.CompanyInfos.Dtos;
using DualControl.CompanyInfos;

namespace DualControl.CompanyInfos
{
    /// <summary>
    /// CompanyInfo应用层服务的接口实现方法  
    ///</summary>
    [AbpAuthorize(CompanyInfoAppPermissions.CompanyInfo)]
    public class CompanyInfoAppService : DualControlAppServiceBase, ICompanyInfoAppService
    {
        private readonly IRepository<CompanyInfo, int> _companyinfoRepository;


        private readonly ICompanyInfoManager _companyinfoManager;

        /// <summary>
        /// 构造函数 
        ///</summary>
        public CompanyInfoAppService(IRepository<CompanyInfo, int> companyinfoRepository
            , ICompanyInfoManager companyinfoManager)
        {
            _companyinfoRepository = companyinfoRepository;
            _companyinfoManager = companyinfoManager;
        }


        /// <summary>
        /// 获取CompanyInfo的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<CompanyInfoListDto>> GetPagedCompanyInfos(GetCompanyInfosInput input)
        {

            var query = _companyinfoRepository.GetAll();
            // TODO:根据传入的参数添加过滤条件

            var companyinfoCount = await query.CountAsync();

            var companyinfos = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            // var companyinfoListDtos = ObjectMapper.Map<List <CompanyInfoListDto>>(companyinfos);
            var companyinfoListDtos = companyinfos.MapTo<List<CompanyInfoListDto>>();

            return new PagedResultDto<CompanyInfoListDto>(companyinfoCount, companyinfoListDtos);
        }


        /// <summary>
        /// 返回当前租户对应的企业概况信息
        /// </summary>
        /// <returns></returns>
        public async Task<CompanyInfoListDto> GetCompanyInfoAsync()
        {
            int? tenantid = AbpSession.TenantId;           
            var entity =await _companyinfoRepository.FirstOrDefaultAsync(info => info.TenantId == tenantid);

            //如果已存在，则返回
            if (entity == null)
            {
                return entity.MapTo<CompanyInfoListDto>();
            }
            return entity.MapTo<CompanyInfoListDto>();
        }


        /// <summary>
        /// 通过指定id获取CompanyInfoListDto信息
        /// </summary>
        public async Task<CompanyInfoListDto> GetCompanyInfoByIdAsync(EntityDto<int> input)
        {
            var entity = await _companyinfoRepository.GetAsync(input.Id);

            return entity.MapTo<CompanyInfoListDto>();
        }

        /// <summary>
        /// MPA版本才会用到的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetCompanyInfoForEditOutput> GetCompanyInfoForEdit(NullableIdDto<int> input)
        {
            var output = new GetCompanyInfoForEditOutput();
            CompanyInfoEditDto companyinfoEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _companyinfoRepository.GetAsync(input.Id.Value);

                companyinfoEditDto = entity.MapTo<CompanyInfoEditDto>();

                //companyinfoEditDto = ObjectMapper.Map<List <companyinfoEditDto>>(entity);
            }
            else
            {
                companyinfoEditDto = new CompanyInfoEditDto();
            }

            output.CompanyInfo = companyinfoEditDto;
            return output;
        }


        /// <summary>
        /// 添加或者修改CompanyInfo的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CreateOrUpdateCompanyInfo(CreateOrUpdateCompanyInfoInput input)
        {

            if (input.CompanyInfo.Id.HasValue)
            {
                await UpdateCompanyInfoAsync(input.CompanyInfo);
            }
            else
            {
                await CreateCompanyInfoAsync(input.CompanyInfo);
            }
        }


        /// <summary>
        /// 新增CompanyInfo
        /// 每个租户对应一条记录
        /// </summary>
        [AbpAuthorize(CompanyInfoAppPermissions.CompanyInfo_Create)]
        protected virtual async Task<CompanyInfoEditDto> CreateCompanyInfoAsync(CompanyInfoEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增
            //查询当前租户有没有数据，如有，则不能增加
            int? tenantid = AbpSession.TenantId;
            var companyinfo = _companyinfoRepository.FirstOrDefault(info=>info.TenantId == tenantid);
            //如果已存在，则返回
            if (companyinfo != null)
            {
                throw new  Exception();
               // return companyinfo.MapTo<CompanyInfoEditDto>();
            }

            //新增加操作
            var entity = ObjectMapper.Map<CompanyInfo>(input);

            entity = await _companyinfoRepository.InsertAsync(entity);
            return entity.MapTo<CompanyInfoEditDto>();
        }

        /// <summary>
        /// 编辑CompanyInfo
        /// </summary>
        [AbpAuthorize(CompanyInfoAppPermissions.CompanyInfo_Edit)]
        protected virtual async Task UpdateCompanyInfoAsync(CompanyInfoEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _companyinfoRepository.GetAsync(input.Id.Value);
            //提交的表单中没有TenantId
            input.TenantId = AbpSession.TenantId.Value;
            input.MapTo(entity);

            // ObjectMapper.Map(input, entity);
            await _companyinfoRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除CompanyInfo信息的方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(CompanyInfoAppPermissions.CompanyInfo_Edit)]
        public async Task DeleteCompanyInfo(EntityDto<int> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _companyinfoRepository.DeleteAsync(input.Id);
        }



        /// <summary>
        /// 批量删除CompanyInfo的方法
        /// </summary>
        [AbpAuthorize(CompanyInfoAppPermissions.CompanyInfo_Edit)]
        public async Task BatchDeleteCompanyInfosAsync(List<int> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _companyinfoRepository.DeleteAsync(s => input.Contains(s.Id));
        }


        /// <summary>
        /// 导出CompanyInfo为excel表,等待开发。
        /// </summary>
        /// <returns></returns>
        //public async Task<FileDto> GetCompanyInfosToExcel()
        //{
        //	var users = await UserManager.Users.ToListAsync();
        //	var userListDtos = ObjectMapper.Map<List<UserListDto>>(users);
        //	await FillRoleNames(userListDtos);
        //	return _userListExcelExporter.ExportToFile(userListDtos);
        //}



        //// custom codes

        //// custom codes end

    }
}


